<?php 
function get_html($filename){
	$wholepath = HTML_PATH.$filename;
	if(file_exists($wholepath)){
		return file_get_contents($wholepath);
	}else{
		return '文件不存在';
	}
}

function assign($key, $value){
	foreach($GLOBALS['__body'] as $kk => $html){
		$regexp = "/\{\\\${$key}\}/i";
		$html = preg_replace($regexp, $value, $html);
		$GLOBALS['__body'][$kk] = $html;
	}
}

function set($html){
	$GLOBALS['__body'][] = $html;
}

function view(){
	global $__body;
	echo get_html('header.tpl');
	echo implode("", $__body);
	echo get_html('footer.tpl');
	ob_flush();
	flush();
}


function genRandomString($len){ 
	$chars = array( 
		"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
		"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
		"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
		"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
		"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
		"3", "4", "5", "6", "7", "8", "9" 
	);
	$charsLen = count($chars) - 1;
	shuffle($chars);    // 将数组打乱
	$output = ""; 
	for ($i=0; $i<$len; $i++){ 
		$output .= $chars[mt_rand(0, $charsLen)];
	}
	return $output;
}

/*******************************************************************************
 * 来自Discuz方法
 *******************************************************************************/
function function_check(&$func_items){
	foreach($func_items as $item){
		if(!function_exists($item)){
			return show_msg('undefine_func', $item, 0);
		}
	}
}

function env_check(&$env_items){
	foreach($env_items as $key => $item){
		if($key == 'php'){
			$env_items[$key]['current'] = PHP_VERSION;
		} elseif($key == 'attachmentupload'){
			$env_items[$key]['current'] = @ini_get('file_uploads') ? ini_get('upload_max_filesize') : 'unknow';
		} elseif($key == 'gdversion'){
			$tmp = function_exists('gd_info') ? gd_info() : array();
			$env_items[$key]['current'] = empty($tmp['GD Version']) ? 'noext' : $tmp['GD Version'];
			unset($tmp);
		} elseif($key == 'diskspace'){
			if(function_exists('disk_free_space')){
				$env_items[$key]['current'] = floor(disk_free_space(ROOT_PATH) / (1024*1024)).'M';
			} else {
				$env_items[$key]['current'] = 'unknow';
			}
		} elseif(isset($item['c'])){
			$env_items[$key]['current'] = constant($item['c']);
		}

		$env_items[$key]['status'] = 1;
		if($item['r'] != 'notset' && strcmp($env_items[$key]['current'], $item['r']) < 0){
			$env_items[$key]['status'] = 0;
		}
	}
}

function dirfile_check(&$dirfile_items){
	foreach($dirfile_items as $key => $item){
		$item_path = $item['path'];
		if($item['type'] == 'dir'){
			if(!dir_writeable(ROOT_PATH.$item_path)){
				if(is_dir(ROOT_PATH.$item_path)){
					$dirfile_items[$key]['status'] = 0;
					$dirfile_items[$key]['current'] = '+r';
				} else {
					$dirfile_items[$key]['status'] = -1;
					$dirfile_items[$key]['current'] = 'nodir';
				}
			} else {
				$dirfile_items[$key]['status'] = 1;
				$dirfile_items[$key]['current'] = '+r+w';
			}
		} else {
			if(file_exists(ROOT_PATH.$item_path)){
				if(is_writable(ROOT_PATH.$item_path)){
					$dirfile_items[$key]['status'] = 1;
					$dirfile_items[$key]['current'] = '+r+w';
				} else {
					$dirfile_items[$key]['status'] = 0;
					$dirfile_items[$key]['current'] = '+r';
				}
			} else {
				if(dir_writeable(dirname(ROOT_PATH.$item_path))){
					$dirfile_items[$key]['status'] = 1;
					$dirfile_items[$key]['current'] = '+r+w';
				} else {
					$dirfile_items[$key]['status'] = -1;
					$dirfile_items[$key]['current'] = 'nofile';
				}
			}
		}
	}
}

function check_db($dbhost, $dbuser, $dbpw, $dbname, $tablepre){
	if(!function_exists('mysql_connect')){
		return show_msg('undefine_func', 'mysql_connect', 0);
	}
	if(!@mysql_connect($dbhost, $dbuser, $dbpw)){
		$errno = mysql_errno();
		$error = mysql_error();
		if($errno == 1045){
			return show_msg('database_errno_1045', $error, 0);
		} elseif($errno == 2003){
			return show_msg('database_errno_2003', $error, 0);
		} else {
			return show_msg('database_connect_error', $error, 0);
		}
	} else {
		if($query = mysql_query("SHOW TABLES FROM $dbname")){
			while($row = mysql_fetch_row($query)){
				if(preg_match("/^$tablepre/", $row[0])){
					return ilang('dbinfo_forceinstall_invalid');
				}
			}
		}
	}
	return 'ok';
}


function dir_writeable($dir){
	$writeable = 0;
	if(!is_dir($dir)){
		@mkdir($dir, 0777);
	}
	if(is_dir($dir)){
		if($fp = @fopen("$dir/test.txt", 'w')){
			@fclose($fp);
			@unlink("$dir/test.txt");
			$writeable = 1;
		} else {
			$writeable = 0;
		}
	}
	return $writeable;
}

function dir_clear($dir){
	global $lang;
	showjsmessage($lang['clear_dir'].' '.str_replace(ROOT_PATH, '', $dir));
	$directory = dir($dir);
	while($entry = $directory->read()){
		$filename = $dir.'/'.$entry;
		if(is_file($filename)){
			@unlink($filename);
		}
	}
	$directory->close();
	@touch($dir.'/index.htm');
}

function ilang($lang_key, $force = true){
	return isset($GLOBALS['lang'][$lang_key]) ? $GLOBALS['lang'][$lang_key] : ($force ? $lang_key : '');
}

function show_env_result(&$env_items, &$dirfile_items, &$func_items){
	global $error_code;
	
	$html = $env_str = $file_str = $dir_str = $func_str = array();
	$error_code = 0;

	foreach($env_items as $key => $item){
		if($key == 'php' && strcmp($item['current'], $item['r']) < 0){
			return show_msg('php_version_too_low', $item['current'], 0);
		}
		$status = 1;
		if($item['r'] != 'notset'){
			if(intval($item['current']) && intval($item['r'])){
				if(intval($item['current']) < intval($item['r'])){
					$status = 0;
					$error_code = ENV_CHECK_ERROR;
				}
			} else {
				if(strcmp($item['current'], $item['r']) < 0){
					$status = 0;
					$error_code = ENV_CHECK_ERROR;
				}
			}
		}
		
		$env_str[] = "<tr>";
		$env_str[] = "<td>".ilang($key)."</td>";
		$env_str[] = "<td>".ilang($item['r'])."</td>";
		$env_str[] = "<td>".ilang($item['b'])."</td>";
		$env_str[] = ($status ? "<td class=\"green\">" : "<td class=\"red\">").$item['current']."</td>";
		$env_str[] = "</tr>";
	}
	$env_str = implode("\n", $env_str);

	foreach($dirfile_items as $key => $item){
		$tagname = $item['type'] == 'file' ? 'File' : 'Dir';
		$variable = $item['type'].'_str';
		
		array_push($$variable, "<tr>");
		array_push($$variable, "<td>$item[path]</td><td class=\"green\">".ilang('writeable')."</td>");
		if($item['status'] == 1){
			array_push($$variable, "<td class=\"green\">".ilang('writeable')."</td>");
		} elseif($item['status'] == -1){
			$error_code = ENV_CHECK_ERROR;
			array_push($$variable, "<td class=\"red\">".ilang('nodir')."</td>");
		} else {
			$error_code = ENV_CHECK_ERROR;
			array_push($$variable, "<td class=\"red\">".ilang('unwriteable')."</td>");
		}
		array_push($$variable, "</tr>");
	}
	$file_str = implode("\n", $file_str);
	$dir_str = implode("\n", $dir_str);

	$html[] = "<table class=\"tb\">";
	$html[] = "<caption>".ilang('env_check')."</caption>";
	$html[] = "<tr>";
	$html[] = "\t<th style=\"width:190px;\">".ilang('project')."</th>";
	$html[] = "\t<th style=\"width:160px;\">".ilang('ucenter_required')."</th>";
	$html[] = "\t<th style=\"width:160px;\">".ilang('ucenter_best')."</th>";
	$html[] = "\t<th>".ilang('curr_server')."</th>";
	$html[] = "</tr>";
	$html[] = $env_str;
	$html[] = "</table>";

	$html[] = "<table class=\"tb\">";
	$html[] = "<caption>".ilang('priv_check')."</caption>";
	$html[] = "\t<tr>";
	$html[] = "\t<th style=\"width:190px;\">".ilang('step1_file')."</th>";
	$html[] = "\t<th style=\"width:160px;\">".ilang('step1_need_status')."</th>";
	$html[] = "\t<th>".ilang('step1_status')."</th>";
	$html[] = "</tr>";
	$html[] = $file_str;
	$html[] = $dir_str;
	$html[] = "</table>";

	foreach($func_items as $item){
		$status = function_exists($item);
		$func_str[] = "<tr>";
		$func_str[] = "<td>$item()</td>";
		if($status){
			$func_str[] = "<td class=\"green\">".ilang('supportted')."</td>";
			$func_str[] = "<td class=\"padleft\">".ilang('none')."</td>";
		} else {
			$error_code = ENV_CHECK_ERROR;
			$func_str[] = "<td class=\"red\">".ilang('unsupportted')."</td>";
			$func_str[] = "<td><font color=\"red\">".ilang('advice_'.$item)."</font></td>";
		}
	}
	$func_str = implode("\n", $func_str);

	$html[] = "<table class=\"tb\">";
	$html[] = "<caption>".ilang('func_depend')."</caption>";
	$html[] = "<tr>";
	$html[] = "\t<th style=\"width:190px;\">".ilang('func_name')."</th>";
	$html[] = "\t<th style=\"width:160px;\">".ilang('check_result')."</th>";
	$html[] = "\t<th>".ilang('suggestion')."</th>";
	$html[] = "</tr>";
	$html[] = $func_str;
	$html[] = "</table>";

	return implode("\n", $html);
}


function show_msg($error_no, $error_msg = 'ok', $success = 1, $quit = TRUE){
		global $step;

		$title = ilang($error_no);
		$comment = ilang($error_no.'_comment', false);
		$errormsg = '';
		$html = array();

		if($error_msg){
			if(!empty($error_msg)){
				foreach ((array)$error_msg as $k => $v){
					if(is_numeric($k)){
						$comment .= "<li><em class=\"red\">".ilang($v)."</em></li>";
					}
				}
			}
		}
		$html[] = "<b>$title</b><ul>$comment</ul>";
		return implode("\n", $html);
}

/*******************************************************************************
 * 运行SQL
 *******************************************************************************/
function runquery($sql, $tablepre) {
	global $__mydb;

	if(!isset($sql) || empty($sql)) return;

	$sql = str_replace("\r", "\n", str_replace('`'.ORIG_TABLEPRE, '`'.$tablepre, $sql));
	$ret = array();
	$num = 0;
	foreach(explode(";\n", trim($sql)) as $query) {
		$ret[$num] = '';
		$queries = explode("\n", trim($query));
		foreach($queries as $query) {
			$ret[$num] .= (isset($query[0]) && $query[0] == '#') || (isset($query[1]) && isset($query[1]) && $query[0].$query[1] == '--') ? '' : $query;
		}
		$num++;
	}
	unset($sql);

	foreach($ret as $query) {
		$query = trim($query);
		if($query) {

			if(substr($query, 0, 12) == 'CREATE TABLE') {
				$temp = preg_replace('/ IF NOT EXISTS /is', ' ', $query);
				$name = preg_replace("/CREATE TABLE `([a-z0-9_]+)` .*/is", "\\1", $temp);
				showjsmessage(ilang('create_table').' '.$name.' ... '.ilang('succeed'));
				$__mydb->query(createtable($query));
			} else {
				$__mydb->query($query);
			}

		}
	}

}

function createtable($sql) {
	$type = strtoupper(preg_replace("/^\s*CREATE TABLE\s+.+\s+\(.+?\).*(ENGINE|TYPE)\s*=\s*([a-z]+?).*$/isU", "\\2", $sql));
	$type = in_array($type, array('MYISAM', 'HEAP')) ? $type : 'MYISAM';
	return preg_replace("/^\s*(CREATE TABLE\s+.+\s+\(.+?\)).*$/isU", "\\1", $sql).
	(mysql_get_server_info() > '4.1' ? " ENGINE=$type DEFAULT CHARSET=".DBCHARSET : " TYPE=$type");
}

function showjsmessage($message) {
	echo '<script type="text/javascript">showmessage(\''.addslashes($message).' \');</script>'."\r\n";
	ob_flush();
	flush();
}

?>